{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "from pathlib import Path\n",
    "import json\n",
    "\n",
    "from conch.open_clip_custom import create_model_from_pretrained\n",
    "from conch.downstream.zeroshot_path import zero_shot_classifier, run_zeroshot\n",
    "\n",
    "import torch\n",
    "import torch.nn.functional as F\n",
    "from torchvision.datasets import ImageFolder\n",
    "from torch.utils.data import DataLoader\n",
    "\n",
    "# display all jupyter output\n",
    "from IPython.core.interactiveshell import InteractiveShell\n",
    "InteractiveShell.ast_node_interactivity = \"all\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "root = Path('../').resolve()\n",
    "os.chdir(root)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This notebook provides a complete example for performing zero-shot classification by ensembling multiple prompts and prompt templates. You can use this notebook to reproduce the zero-shot classification results on CRC100K (image size = 224 x 224). "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model_cfg = 'conch_ViT-B-16'\n",
    "device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n",
    "checkpoint_path = './checkpoints/CONCH/pytorch_model.bin'\n",
    "force_image_size = 224\n",
    "model, preprocess = create_model_from_pretrained(model_cfg, checkpoint_path, device=device,\n",
    "                                                 force_image_size=force_image_size)\n",
    "_ = model.eval()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data_source = '/path/to/CRC100k/validation/set'\n",
    "dataset = ImageFolder(data_source, transform=preprocess)\n",
    "dataloader = DataLoader(dataset, batch_size=64, shuffle=False, num_workers=4)\n",
    "if hasattr(dataloader.dataset, 'class_to_idx'):\n",
    "     idx_to_class = {v:k for k,v in dataloader.dataset.class_to_idx.items()}\n",
    "else:\n",
    "     raise ValueError('Dataset does not have label_map attribute')\n",
    "print(\"num samples: \", len(dataloader.dataset))\n",
    "print(idx_to_class)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "prompt_file = './prompts/crc100k_prompts_all_per_class.json'\n",
    "with open(prompt_file) as f:\n",
    "    prompts = json.load(f)['0']\n",
    "classnames = prompts['classnames']\n",
    "templates = prompts['templates']\n",
    "n_classes = len(classnames)\n",
    "classnames_text = [classnames[str(idx_to_class[idx])] for idx in range(n_classes)]\n",
    "for class_idx, classname in enumerate(classnames_text):\n",
    "    print(f'{class_idx}: {classname}')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "zeroshot_weights = zero_shot_classifier(model, classnames_text, templates, device=device)\n",
    "print(zeroshot_weights.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "results, dump = run_zeroshot(model, zeroshot_weights, dataloader, device, \n",
    "                    dump_results=True, metrics=['bacc', 'weighted_f1'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for k, v in results.items():\n",
    "    print(f'{k}: {v:.3f}')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "conch",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
